import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../views/Layout.vue'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)
const routes = [
  {
    path: '/login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/article/:id',
    component: () => import('../views/Detail.vue')
  },
  {
    path: '/',
    redirect: '/article',
    component: Layout,
    children: [
      {
        path: 'article',
        component: () => import('../views/Article.vue')
      },
      {
        path: 'like',
        component: () => import('../views/Like.vue')
      },
      {
        path: 'collect',
        component: () => import('../views/Collect.vue')
      },
      {
        path: 'user',
        component: () => import('../views/User.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const token = getToken()
  if (to.path === '/login' || to.path === '/register') {
    next()
  } else if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
